package com.example.demo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.util.List;


public class JsonTest {
    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static List<JSONObject> getJsonList(String jsonName){
        String path = JsonTest.class.getClassLoader().getResource(jsonName).getPath();
        String s = JsonTest.readJsonFile(path);
        JSONObject jobj = JSON.parseObject(s);
        //转化成JSON数组 不止一条数据
        JSONArray jsonArray = jobj.getJSONArray("Departments");
        //JSONArray转List
        List<JSONObject> list = JSONObject.parseArray(jsonArray.toJSONString(), JSONObject.class);
        return list;
    }

}
